import logging
from flask import render_template, session, abort, g, jsonify, request
from info import constants, db
from info.models import News, User, Comment, CommentLike
from info.response_code import RET
from info.utils.common import user_login_data
from . import news_blue


@news_blue.route('/detail/<int:news_id>')
@user_login_data
def news_detail(news_id):
    """
    新闻详情视图
    :param news_id: 新闻id
    :return: 新闻详情
    1.查询用户基本信息
    2.查询点击排行信息
    3.查询新闻内容
    4.判断当前用户是否收藏新闻

    """
    # 1.查询用户基本信息
    user = g.user
    # user_id = session.get('user_id')
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         logging.error(e)
    # 2.查询点击排行信息
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        logging.error(e)

    click_news_list = []
    for news in news_list if news_list else []:
        click_news_list.append(news.to_basic_dict())
    # 3.查询新闻内容
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
    if not news:
        abort(404)
    # 更新新闻的点击量
    news.clicks += 1
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
    # 4.判断当前用户是否收藏新闻
    is_collected = False
    # 7.判断当前用户是否关注当前新闻作者
    is_followed = False
    is_show = False
    if user:
        if news in user.collection_news:
            is_collected = True
    try:
        news_user = User.query.filter(User.id == news.user_id).first()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')
    if news_user:
        is_show = True
        if user in news_user.followers:
            is_followed = True
    # 5.显示新闻评论内容
    comment_dict_list = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')
    comments_like_ids = []
    if user:
        try:
            comment_likes = CommentLike.query.filter(CommentLike.user_id == user.id).all()
            comments_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            logging.error(e)
    for comment in comments:
        # 6.显示点赞数及用户点赞情况
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False
        if comment.id in comments_like_ids:
            comment_dict['is_like'] = True
        comment_dict_list.append(comment_dict)

    context = {
        'user': user.to_dict() if user else None,
        'click_news_list': click_news_list,
        'news': news.to_dict(),
        'is_collected': is_collected,
        'comments': comment_dict_list,
        'is_followed': is_followed,
        'is_show': is_show

    }

    return render_template('news/detail.html', context=context)


@news_blue.route('/news_collect', methods=['GET', 'POST'])
@user_login_data
def news_collect():
    """
    新闻收藏与取消收藏视图
    1.获取登录用户的参数
    2.获取要收藏或者取消的新闻id，和收藏或者取消收藏的action
    3.判断参数（先判断用户是否登录，未登录则不能收藏，提示登录，然后判断参数是否齐全，最后判断action是否在指定范围内）
    4.查询要收藏或者取消收藏的新闻
    5.收藏或取消收藏
    6.返回响应
    """
    user = g.user
    json_dict = request.json
    news_id = json_dict.get('news_id')
    action = json_dict.get('action')
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据失败')
    if not news:
        return jsonify(errno=RET.DATAERR, errmsg='查询的数据不存在')
    if action == 'collect':
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存失败')
    return jsonify(errno=RET.OK, errmsg='OK')


@news_blue.route('/news_comment', methods=['GET', 'POST'])
@user_login_data
def news_comment():
    """
    新闻评论
    1.获取用户的信息
    2.获取参数（评论的新闻id，评论的内容，被回复评论的id）
    3.校验参数
    4.检查新闻是否存在
    5.初始化评论模型，并赋值，同步到数据库
    6.响应评论结果
    7.在新闻详情视图函数中渲染评论内容
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    json_dict = request.json
    news_id = json_dict.get('news_id')
    comment_content = json_dict.get('comment')
    parent_id = json_dict.get('parent_id')
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not news:
        return jsonify(errno=RET.DATAERR, errmsg='新闻不存在')
    comment = Comment()
    comment.user_id = user.id
    comment.content = comment_content
    comment.news_id = news_id
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存储数据失败')

    return jsonify(errno=RET.OK, errmsg='OK', data=comment.to_dict())


@news_blue.route('/comment_like', methods=['GET', 'POST'])
@user_login_data
def comment_like():
    """
    点赞
    1.获取用户信息
    2.获取参数（评论的id，action）
    3.判断参数是否齐全及action是否在范围内
    4.查询要点赞或者取消点赞的评论
    5.点赞或取消点赞
    6.返回响应
    7.在新闻详情视图函数中渲染用户的点赞信息
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    json_dict = request.json
    comment_id = json_dict.get('comment_id')
    action = json_dict.get('action')
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    if action not in ['add', 'remove']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        comment_id = int(comment_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据库失败')
    if not comment:
        return jsonify(errno=RET.DATAERR, errmsg='评论不存在')
    comment_like_model = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                  CommentLike.user_id == user.id).first()
    if action == 'add':
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.user_id = user.id
            comment_like_model.comment_id = comment_id
            db.session.add(comment_like_model)
            comment.like_count += 1
    else:
        if comment_like_model:
            db.session.delete(comment_like_model)
            comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存储数据失败')
    return jsonify(errno=RET.OK, errmsg='OK')


@news_blue.route('/followed_user', methods=['GET', 'POST'])
@user_login_data
def followed_user():
    """
    关注新闻作者
    1.获取当前用户参数
    2.获取参数（被关注用户的id，关注或取消的动作action）
    3.判断参数是否齐全，action是否在范围内（follow， unfollow）
    4.获取当前新闻作者的信息
    5.获取当前新闻作者的粉丝集
    6.判断action，如果为follow则先判断是否已收藏，没有则添加关注，如果为unfollow，则判断是否已收藏，收藏则取消收藏
    7.同步数据库
    8.返回响应数据
    """
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    json_dict = request.json
    user_id = json_dict.get('user_id')
    action = json_dict.get('action')
    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    if action not in ['follow', 'unfollow']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news_user = User.query.get(user_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')
    if action == 'follow':
        if user not in news_user.followers:
            news_user.followers.append(user)
    else:
        if user in news_user.followers:
            news_user.followers.remove(user)
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='同步数据库失败')

    return jsonify(errno=RET.OK, errmsg='OK')

